package com.sunyard.manage.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSONObject;
import com.ctg.ag.sdk.biz.AepDeviceCommandClient;
import com.ctg.ag.sdk.biz.aep_device_command.CreateCommandRequest;
import com.ctg.ag.sdk.biz.aep_device_command.CreateCommandResponse;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.sunyard.constant.ErrMessageConst;
import com.sunyard.dal.bo.sys.AuditPasswordBo;
import com.sunyard.dal.bo.PaginationBO;
import com.sunyard.dal.bo.task.*;
import com.sunyard.dal.dto.OtherParamDTO;
import com.sunyard.dal.dto.znsTask.*;
import com.sunyard.dal.entity.*;
import com.sunyard.dal.mapper.*;
import com.sunyard.enums.LockTypeEnum;
import com.sunyard.enums.TerminalTypeEnum;
import com.sunyard.manage.constant.TblLogConst;
import com.sunyard.manage.service.OperatorLogService;
import com.sunyard.manage.service.OperatorService;
import com.sunyard.manage.service.OrganizationService;
import com.sunyard.manage.service.TaskService;
import com.sunyard.manage.util.StringUtil;
import com.sunyard.utils.*;
import com.sunyard.utils.Response.BaseResult;
import com.sunyard.utils.Response.GetResult;
import com.sunyard.utils.Response.HeaderResult;
import com.sunyard.utils.manage.DataGrid;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.log.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * @author jimin.duan
 * @Description TODO
 * @createTime 2022年06月24日 17:02:00
 */
@Slf4j
@Service
public class TaskServiceImpl implements TaskService {

    @Autowired
    private ZNSTaskMapper znsTaskMapper;

    @Autowired
    private OperatorLogService operatorLogService;

    @Autowired
    private TerminalMapper terminalMapper;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private OperatorMapper operatorMapper;

    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    OtherParamMapper otherParamMapper;

    /**
     * 添加任务
     *
     * @param taskADDBO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult addTask(TaskADDBO taskADDBO, HttpServletRequest request) throws Exception {
        log.info("添加任务请求参数：{}", JSONUtil.toJsonStr(taskADDBO));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        List<String> list = new ArrayList<>();
        list.add(OtherParam.TASK_ADD_AUTH);
        List<OtherParamDTO> otherParams = otherParamMapper.queryByKeys(list);
        //先判断锁具是否对应人员
        if (taskADDBO.getAssociatedTrunkLockType() == null) {
            String lockMode1 = taskADDBO.getLockMode();
            if ("1".equals(lockMode1)) {
                //单人开锁
                String locksn = taskADDBO.getLocksn();
                if (locksn.length() != 0) {
                    String lockName = taskADDBO.getLockName();
                    if (lockName.length() == 0) {
                        return GetResult.getResultFail("单人开锁模式 请锁跟人员对应(勾选柜员锁必须有柜员人员，勾选主管锁必须有主管人员)");
                    }
                }
            }
            if ("1".equals(taskADDBO.getBranchOrgIDLockMode())) {
                String locksn = taskADDBO.getLocksn();
                if (locksn.length() != 0) {
                    String branchOrgIDOP = taskADDBO.getBranchOrgIDOP();
                    if (branchOrgIDOP.length() == 0) {
                        return GetResult.getResultFail("单人开锁模式 请锁跟人员对应(勾选柜员锁必须有柜员人员，勾选主管锁必须有主管人员)");
                    }
                }
            }
        }
        /*if (StringUtils.isNotBlank(taskADDBO.getLockName())){
            List<String> list = Arrays.asList(taskADDBO.getLockName().split(","));
            List<Terminal> terminals = terminalMapper.selectByNames(list);
            List<String> listSn = Arrays.asList(taskADDBO.getLocksn().split(","));
            for (Terminal terminal : terminals) {
                if (!listSn.contains(terminal.getTerminalSn())){
                    return GetResult.getResultFail("锁具sn和名称对应错误!");
                }
            }
        }*/
        //插入数据之前 总数
        Integer countBefore = znsTaskMapper.selectcount();
//        try {
        //获取安全策略 1锁具唯一 2 开锁唯一 3 不生效 4 谁关谁开
        String securityPolicy = taskADDBO.getSecurityPolicy();
        //锁具唯一 查看锁是否有任务 且未超过最后结束时间
        if ("1".equals(securityPolicy)) {
            String openLockOP = taskADDBO.getOpenLockOP();
            String[] split1 = new String[0];
            if (StringUtils.isNotBlank(openLockOP)) {
                split1 = openLockOP.split(",");
            }
            if ("1".equals(taskADDBO.getLockMode())) {
                if (split1.length != 1) {
                    return GetResult.getResultFail("添加任务失败,单人开锁模式锁具唯一任务只能选择一人");
                }
            }
            if ("2".equals(taskADDBO.getLockMode())) {
                if (split1.length != 2) {
                    return GetResult.getResultFail("添加任务失败,双人开锁模式锁具唯一任务只能选择两人");
                }
            }
            String locksn = taskADDBO.getLocksn();
            String zh = locksn;
            String[] split = zh.split(",");
            for (String lockSn : split) {
                if (StringUtils.isNotBlank(lockSn)) {
                    Integer integer = znsTaskMapper.selectforLockOnly("%" + lockSn + "%");
                    if (integer > 0) {
                        return GetResult.getResultFail("添加任务失败,锁" + lockSn + "还有未结束任务");
                    }
                }
            }
        }
        //定义公共参数map
        HashMap<String, Object> maps = new HashMap<>();
        if (!org.springframework.util.CollectionUtils.isEmpty(otherParams)){
            OtherParam otherParam = otherParams.get(0);
            if ("0".equals(otherParam.getConfValue()) ) {
                taskADDBO.setAuditor(opId);
                maps.put("auditState", "2");
            }
        }
        maps.put("securityPolicy", taskADDBO.getSecurityPolicy());
        maps.put("taskTypeName", taskADDBO.getTaskTypeName());
        //任务所属机构
        maps.put("orgId", taskADDBO.getOrgIDforTask());
        //根据机构号查名称
        String nameById = znsTaskMapper.findNameById(taskADDBO.getOrgIDforTask());

        maps.put("orgName", nameById);
        maps.put("whoOpenWhoClose", taskADDBO.getWhoOpenWhoClose());
        maps.put("onceTheLock", taskADDBO.getOnceTheLock());
        maps.put("transportEscorts", taskADDBO.getTransportEscorts());
        maps.put("transportCar", taskADDBO.getTransportCar());
        maps.put("transportCompany", taskADDBO.getTransportCompany());
        maps.put("taskState", "1");
        //审核人编号
        maps.put("auditor", taskADDBO.getAuditor());
        maps.put("issuedState", "2");
        //创建人编号
        maps.put("createOP", taskADDBO.getCreateOP());
        //当前登录机构编号
        // maps.put("orgId", taskADDBO.getOrgId());
        maps.put("associatedTrunkLockType", taskADDBO.getAssociatedTrunkLockType());
        //获取尾箱类型
        String associatedTrunkLockType = taskADDBO.getAssociatedTrunkLockType();
        if (associatedTrunkLockType != null) {
//            物联网尾箱（绑定一把锁） 可以远程开锁 不会传递锁具 后台查询对应锁具
            if ("0".equals(associatedTrunkLockType)) {
                String trunkId = taskADDBO.getTrunkId();
//                trunkId="111,222,333";
                //
                String trunkNames = "";
                String[] split = trunkId.split(",");
                for (String s : split) {
                    //根据尾箱编号 查询尾箱名称 放入maps中
                    String trunkName = znsTaskMapper.trunkNameById(s);
                    if (!"".equals(trunkNames)) {
                        trunkNames = trunkNames + "," + trunkName;
                    }
                    //根据物联网尾箱编号查询对应锁具 以及锁具类型 主管 or 柜员  然后将主管锁或柜员锁赋值
                    //根据尾箱编号查询锁具编号
                    Map<String, String> lockIds = znsTaskMapper.findLockByBox(s);
                    String trunkLockOne = lockIds.get("trunkLockOne");
                    String trunkLockTwo = lockIds.get("trunkLockTwo");
                    List<LockDTO> all = new ArrayList<LockDTO>();
                    //根据锁具编号查询锁具
                    List<LockDTO> lockById = znsTaskMapper.findLockById(trunkLockOne);
                    all.addAll(lockById);
                    System.out.println(all + "what");
                    String lockType = all.get(0).getLockType();
                    String lockName = all.get(0).getLockName();
                    String lockId = all.get(0).getLockSn();
                    taskADDBO.setLockName(lockName);
                    taskADDBO.setLocksn(lockId);
                }
                maps.put("trunkId", trunkId);
                maps.put("trunkName", trunkNames);
            } else if ("1".equals(associatedTrunkLockType)) {
                String trunkId = taskADDBO.getTrunkId();
                String trunkNames = "";
                String[] split = trunkId.split(",");
                for (String s : split) {
                    //根据尾箱编号 依次查询尾箱名称 拼接成字符串放入maps中
                    String trunkName = znsTaskMapper.trunkNameById(s);
                    if (!"".equals(trunkNames)) {
                        trunkNames = trunkNames + "," + trunkName;
                    }
                }
                //无缘尾箱
                maps.put("trunkId", trunkId);
                maps.put("trunkName", trunkNames);
            }
        }
        // 首先获取任务时限类型 "任务时限类型  1 长期设置 2 日期设置 3 周设置
        String timeType = taskADDBO.getTimeType();

        if ("1".equals(timeType)) {
            maps.put("timeType", timeType);
            // 2022-08-08 00:00:00,2022-08-23 00:00:00
            String[] split = taskADDBO.getDateTime().split(",");
            String substring = split[0].substring(5, 7);
            String substring2 = split[1].substring(5, 7);
            /*if (!substring.equals(substring2)) {
                return GetResult.getResultFail("任务时限未选择当月");
            }*/
            String replace = taskADDBO.getDateTime().replace(",", " - ");
            String deadLineDate = replace.substring(22);
            maps.put("dateTime", replace);
            maps.put("dayDate", null);
            maps.put("dayTime", null);
            maps.put("weekType", null);
            maps.put("weekDay", null);
            maps.put("startTime", taskADDBO.getDateTime().substring(0, 19));
            maps.put("deadLineDate", deadLineDate);
        } else if ("2".equals(timeType)) {
            maps.put("timeType", timeType);
            maps.put("dateTime", null);
            String dayDate = taskADDBO.getDayDate();
            String[] split = dayDate.split(",");
            //获取开始天数
            String beginday = split[0].trim();
            // 获取最后的天数
            String day = split[split.length - 1].trim();
            maps.put("dayDate", taskADDBO.getDayDate());
            // 10:29:25,11:29:25
            maps.put("dayTime", taskADDBO.getDayTime());
            String substring = taskADDBO.getDayTime().substring(0, 8);
            String daytime = taskADDBO.getDayTime().substring(9);
            maps.put("weekType", null);
            maps.put("weekDay", null);
            maps.put("startTime", beginday + " " + substring);
            maps.put("deadLineDate", day + " " + daytime);
        } else if ("3".equals(timeType)) {
            maps.put("timeType", timeType);
            maps.put("dateTime", null);
            maps.put("dayDate", null);
            maps.put("dayTime", taskADDBO.getDayTime());
            maps.put("weekType", taskADDBO.getWeekType());
            maps.put("weekDay", taskADDBO.getWeekDay());
            //先判断周类型 1 近一周 2 近一月 3近一年
            String weekType = taskADDBO.getWeekType();
            if ("1".equals(weekType)) {
                String daytime = taskADDBO.getDayTime().substring(9);
                String startTime = taskADDBO.getDayTime().substring(0, 9);
                //加7天
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date date = new Date();
                long time = date.getTime();
                long weektime = 7 * 24 * 60 * 60 * 1000;
                String format = simpleDateFormat.format(new Date(time + weektime));
                maps.put("startTime", simpleDateFormat.format(new Date()));
                maps.put("deadLineDate", format + " " + daytime);
            } else if ("2".equals(weekType)) {
                String daytime = taskADDBO.getDayTime().substring(9);
                String startTime = taskADDBO.getDayTime().substring(0, 9);
                //加30天
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date date = new Date();
                long time = date.getTime();
                long weektime = 30 * 24 * 60 * 60 * 1000L;
                String format = simpleDateFormat.format(new Date(time + weektime));
                maps.put("startTime", simpleDateFormat.format(new Date()));
                maps.put("deadLineDate", format + " " + daytime);
            } else {
                String daytime = taskADDBO.getDayTime().substring(9);
                String startTime = taskADDBO.getDayTime().substring(0, 9);
                //加一年
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date date = new Date();
                long time = date.getTime();
                long weektime = 365 * 24 * 60 * 60 * 1000L;
                String format = simpleDateFormat.format(new Date(time + weektime));
                maps.put("startTime", simpleDateFormat.format(new Date()));
                maps.put("deadLineDate", format + " " + daytime);
            }
        } else {
            return GetResult.getResultFail("任务时限类型输入错误,请输入正确的类型");
        }

        String deadLineDate = (String) maps.get("deadLineDate");
        Date endDate = DateUtil.getDate("yyyy-MM-dd HH:mm:ss", deadLineDate);
        Date now = new Date();
        if(endDate.before(now)){
            return GetResult.getResultFail("任务结束时间不能小于当前时间");
        }

        //获取开锁人
        String openLockOP = taskADDBO.getOpenLockOP();
        //获取锁
        String lockName = taskADDBO.getLockName();
        log.info("柜员锁名称={}", lockName);
        //获取锁sn码
        String locksn = taskADDBO.getLocksn();
        log.info("柜员锁sn码={}", locksn);

        //判断是否勾选调拨
        String branchOrgID = taskADDBO.getBranchOrgID();
        String branchOrgName = taskADDBO.getBranchOrgName();
        //获取开锁模式 单人或双人  1 单人 2 双人
        String lockMode = taskADDBO.getLockMode();
        //获取分库行开锁模式
        String branchOrgIDLockMode = taskADDBO.getBranchOrgIDLockMode();
        //获取分行库开锁人
        String branchOrgIDOP = taskADDBO.getBranchOrgIDOP();
        if (StringUtils.isNotBlank(branchOrgID)) {
            maps.put("lockType", 1);
            maps.put("brcOrgId", branchOrgID);
            maps.put("brcOrgName", branchOrgName);
            maps.put("brcOrgMode", branchOrgIDLockMode);
            maps.put("brcOrgIdOp", branchOrgIDOP);
        }
        //切割锁具。每25把生成一批任务
        if (!StringUtils.isNotBlank(locksn)) {
            return GetResult.getResultFail("任务创建失败 锁具不能为空");
        }

        Map<String, String> lockSnNameMap = new HashMap<>();
        String[] snSplit = locksn.split(",");
        if (25 < snSplit.length) {
            List<String> lockSnList = Arrays.asList(snSplit);
            List<Terminal> terminalList = terminalMapper.getTerminalByListSn(lockSnList);
            if (CollectionUtil.isEmpty(terminalList) || terminalList.size() != snSplit.length) {
                return GetResult.getResultFail("任务创建失败 锁具sn号不存在，请确认");
            }

            int count = 0;
            StringBuilder lockNameSB = new StringBuilder();
            StringBuilder lockSnSB = new StringBuilder();
            for (int i = 0; i < terminalList.size(); i++) {
                Terminal terminal = terminalList.get(i);
                lockNameSB.append(terminal.getName());
                lockSnSB.append(terminal.getTerminalSn());
                ++count;
                if (count >= 25 || i + 1 == terminalList.size()) {
                    lockSnNameMap.put(lockSnSB.toString(), lockNameSB.toString());
                    count = 0;
                    lockNameSB = new StringBuilder();
                    lockSnSB = new StringBuilder();
                } else {
                    lockNameSB.append(",");
                    lockSnSB.append(",");
                }
            }

        } else {
            lockSnNameMap.put(locksn, lockName);
        }

        Set<Map.Entry<String, String>> entries = lockSnNameMap.entrySet();
        if ("1".equals(lockMode)) {
            //生成单人任务
            //一条任务锁具不能超过30把
            // 添加单人任务
            for (Map.Entry<String, String> entry : entries) {
                locksn = entry.getKey();
                lockName = entry.getValue();
                oneOpen(openLockOP, maps, lockName, locksn);
                branchOpen(branchOrgID, branchOrgIDLockMode, branchOrgIDOP, taskADDBO, maps, lockName, locksn);
            }
        } else {
            //本行库双人开锁模式
            String orgIDforTask = taskADDBO.getOrgIDforTask();
            String nameById1 = znsTaskMapper.findNameById(orgIDforTask);

            for (Map.Entry<String, String> entry : entries) {
                locksn = entry.getKey();
                lockName = entry.getValue();
                doubleOpenLock(openLockOP,locksn, lockName, orgIDforTask, nameById1, maps);
                branchOpen(branchOrgID, branchOrgIDLockMode, branchOrgIDOP, taskADDBO, maps, lockName, locksn);
            }
        }
        Integer countAfter = znsTaskMapper.selectcount();
        //获取插入了多少条数据
        int total = countAfter - countBefore;
        //查询插入的任务id
        List<String> strings = znsTaskMapper.selectInsertID(total);
        BaseResult<Object> objectBaseResult = new BaseResult<>();
        if (strings != null && strings.size() > 0) {
            Map<String, String> stringStringMap = znsTaskMapper.selectIdAndNameById(taskADDBO.getCreateOP());
            String opName = stringStringMap.get("opName");
            String operationDesc = opName + "添加了任务编号为:" + strings + "的任务";
            operatorLogService.insert(operationDesc, TblLogConst.TASK_ADD, "1", taskADDBO.getCreateOP(), opName, taskADDBO.getOrgId());
            objectBaseResult.setData(strings);
            objectBaseResult.setDataMessage("添加任务成功 ");
            objectBaseResult.setDataCode("00");
        } else {
            objectBaseResult.setData(null);
            objectBaseResult.setDataMessage("添加任务失败");
            objectBaseResult.setDataCode("01");
        }
        return objectBaseResult;
    }

    /**
     * 给机构绑定锁具
     */
    private void addLockForORG(String lockSn, String lockName, String org, String taskTypeName, String createOp, String type, String deadTime, String startTime) {
        //给分库行机构 添加锁具
        Map<Object, Object> maptool = new HashMap<>();
        //将所有锁进行组合
        //String[] gyLocks = lockName.split(",");
        String[] gyLocks = lockSn.split(",");
        for (String lock : gyLocks) {
            // lock 单个柜员锁名称
            // maptool.put("name", lock);
            // String lockSN = znsTaskMapper.selectlockSnbyName(lock);
            // maptool.put("terminalsn", lockSN);
            // //所属机构
            // maptool.put("orgId", org);
            // //锁类型
            // maptool.put("lockType", type);
            // //锁场景
            // maptool.put("missiontype", taskTypeName);
            // //张三,111
            // maptool.put("createuser", createOp);
            // maptool.put("status", "0");
            // maptool.put("lockstatus", "1");
            // maptool.put("effect_time", deadTime);
            // znsTaskMapper.insertLockToLock(maptool);

            Terminal terminal = terminalMapper.getTerminalBySn(lock, TerminalTypeEnum.LOCK.getCode());
            if (StringUtils.isNotBlank(terminal.getOldOrg()) && StringUtils.isNotBlank(terminal.getEffectTime()) &&  dateContrast(terminal.getEffectTime())){
                throw new RuntimeException("已经调拨过的锁具不能再次调拨!");
            }
            String oldOrg = terminal.getOrgId();
            terminal.setOrgId(org);
            terminal.setEffectTime(deadTime);
            //重复调拨时旧组织机构变更问题
            if (StringUtils.isNotBlank(terminal.getOldOrg())){
                terminal.setOldOrg(terminal.getOldOrg());
            } else {
                terminal.setOldOrg(oldOrg);
            }
            terminal.setStartTime(startTime);
            terminalMapper.updateByPrimaryKeySelective(terminal);
        }
    }

    /**
     * 时间对比 -- 与当前时间做对比，如果当前时间小于有效期返回true，如果大于或等于当前时间返回false
     * @param effectTime
     * @return
     */
    public boolean dateContrast(String effectTime){
        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowDate = df.format(date);
        System.out.println(effectTime);
        System.out.println(nowDate);
        int i = nowDate.compareTo(effectTime);
        if (-1 == i){
            return true;
        } else {
            return false;
        }
    }

    /**
     * 双人开锁
     */
    private void doubleOpenLock(String openLockOP,String lockSn, String lockNam,
                                String orgId, String orgName, Map<String, Object> maps) throws Exception {
        ArrayList<Terminal> terminals = new ArrayList<Terminal>();
        if (StringUtils.isNotBlank(openLockOP)) {
            //获取锁列表
            String[] lockSns = lockSn.split(",");
            //将柜员锁和柜员通锁数据分开
            for (String sn : lockSns) {
                Terminal terminal = terminalMapper.getTerminalBySn(sn,TerminalTypeEnum.LOCK.getCode());
//                if (ObjectUtil.isNotNull(terminal) && LockTypeEnum.EMPLOYEE.getCode().equals(terminal.getLockType())) {
//                    throw new Exception("双人开锁模式不能选择柜员锁");
//                }
                terminals.add(terminal);
            }
        }
        // if (StringUtils.isBlank(lockZGName) && StringUtils.isNotBlank(openZGLockOP)) {
        //     throw new Exception("主管锁不能为空");
        // }
        System.out.println(lockNam + "=====");
        String s = "";
        if (!"".equals(openLockOP)) {
            s = openLockOP;
        }
        ArrayList<String> strings = new ArrayList<>();
        String[] split = s.split(",");
        for (int i = 0; i < split.length - 1; i++) {
            for (int j = i + 1; j <= split.length - 1; j++) {
                String str = split[i] + "," + split[j];
                strings.add(str);
            }
        }
        //柜员锁列表
        List<Terminal> gyList = new ArrayList<>();
        //通用锁列表
        List<Terminal> tyList = new ArrayList<>();
        //将柜员锁和柜员通锁数据分开
        for (Terminal terminal : terminals) {
            if (LockTypeEnum.EMPLOYEE.getCode().equals(terminal.getLockType())) {
                gyList.add(terminal);
            } else if (LockTypeEnum.EMPLOYEE_GENERAL.getCode().equals(terminal.getLockType())) {
                tyList.add(terminal);
            }
        }
        List<String> tyNameList = tyList.stream().map(item -> item.getName()).collect(toList());
        //定义所有开锁组合集合
        HashMap<String, String> objectObjectHashMap = new HashMap<>();
        for (String object : strings) {
            List<String> arrayList = new ArrayList<>();
            arrayList.addAll(tyNameList);
            String[] split1 = object.split(",");
            if (split1.length != 2) {
                throw new Exception("人员分组失败");
            } else {
                String s1 = StringUtil.last(split1[0]);
                String s2 = StringUtil.last(split1[1]);
                if (!gyList.isEmpty()) {
                    for (Terminal terminal : gyList) {
                        Operator operator = operatorMapper.getOperatorByOpId(terminal.getAdminId());
                        if (String.valueOf(operator.getId()).equals(s1) || String.valueOf(operator.getId()).equals(s2)) {
                            arrayList.add(terminal.getName());
                        }
                    }
                    objectObjectHashMap.put(object, String.join(",", arrayList));
                } else {
                    // 管理全部锁
                    objectObjectHashMap.put(object, lockNam);
                }
            }
        }
        System.out.println(objectObjectHashMap + "所有锁与人组合");
//        //所有开锁人组合
        Set<String> ksrs = objectObjectHashMap.keySet();
        for (String ksr : ksrs) {
            //开锁人对应的锁具
            String lockName = objectObjectHashMap.get(ksr);
            maps.put("orgId", orgId);
            maps.put("orgName", orgName);
            String openlockop = "";
            String openlockopOrg = "";
            String[] split1 = ksr.split(",");
            for (String s1 : split1) {
                String before = StringUtil.lastBefore(s1);
                String after = StringUtil.last(s1);

                if ("".equals(openlockop)) {
                    openlockop = before;
                } else {
                    openlockop = openlockop + "," + before;
                }
                if ("".equals(openlockopOrg)) {
                    openlockopOrg = after;
                } else {
                    openlockopOrg = openlockopOrg + "," + after;
                }
            }
            maps.put("lockMode", "2");
            //开锁人
            maps.put("openlockop", openlockop);
            //开锁人所属机构
            maps.put("openlockopOrg", openlockopOrg);
            maps.put("lockName", lockName);
            //主键
            String primaryKey = genUniqueKey();
            maps.put("taskID", primaryKey);
            String[] split2 = lockName.split(",");
            String locksn = lockSn.replace(",","/");
            String ss = "";
         /*   for (String s1 : split2) {
                //根据锁名称查询锁sn码
                String locksns = znsTaskMapper.selectlockSnbyName(s1);
                if ("".equals(ss)) {
                    ss = locksns;
                } else {
                    ss = ss + "/" + locksns;
                }
            }*/
            maps.put("locksn", locksn);
            if (lockName.split(",").length <= 30) {
                znsTaskMapper.addTask(maps);
                Map<Object, Object> taskCopyMap = new HashMap<>();
                String primaryKey2 = PrimaryKeyUtil.getPrimaryKey();
                String auditor = (String) maps.get("auditor");
                String createOP = (String) maps.get("createOP");
                //审核表主键
                //根据编号查询所属机构及名称
                Map<String, String> auditMap = znsTaskMapper.selectIdAndNameById(auditor);
                taskCopyMap.put("AUDIT_OPId", auditor);
                taskCopyMap.put("AUDIT_OP", auditMap.get("opName"));
                taskCopyMap.put("AUDIT_OP_ORG", auditMap.get("orgId"));
                Map<String, String> createOPMap = znsTaskMapper.selectIdAndNameById(createOP);
                taskCopyMap.put("CREATE_AUDIT_OPId", createOP);
                taskCopyMap.put("CREATE_AUDIT_OP", createOPMap.get("opName"));
                taskCopyMap.put("CREATE_AUDIT_OP_ORG", createOPMap.get("orgId"));
                taskCopyMap.put("auditId", primaryKey2);
                taskCopyMap.put("taskId", primaryKey);
                taskCopyMap.put("auditaction", "添加任务编号为：" + primaryKey + "的任务");
                //查询当前登录机构的审核模式 同步or异步
                String orgIds = (String) maps.get("orgId");
                String auditType = znsTaskMapper.selectAuditType(orgIds);
                if ("1".equals(auditType)) {
                    //同步审核
                    taskCopyMap.put("auditTime", DateUtil.getDateStr(DateUtil.YYYYMMDD_HHMMSS, new Date()));
                    taskCopyMap.put("auditState", '2');
                } else {
                    taskCopyMap.put("auditTime", null);
                    taskCopyMap.put("auditState", '1');
                }
                //审核表主键
                taskCopyMap.put("auditId", primaryKey2);
                taskCopyMap.put("taskId", primaryKey);
                taskCopyMap.put("auditaction", "添加任务编号为：" + primaryKey + "的任务");
                znsTaskMapper.insertTaskCopy(taskCopyMap);
            } else {
                return;
            }
        }
    }

    private void branchOpen(String branchOrgID, String branchOrgIDLockMode, String branchOrgIDOP, TaskADDBO taskADDBO, Map<String, Object> maps, String lockName, String locksn) throws Exception {
        //勾选调拨 生成分库行主管 跟柜员任务
        if (StringUtils.isNotBlank(branchOrgID)) {
            maps.put("lockType", null);
            maps.put("brcOrgId", null);
            maps.put("brcOrgName", null);
            maps.put("brcOrgMode", null);
            maps.put("brcOrgIdOp", null);
            //调拨分库行单人开锁
            if ("1".equals(branchOrgIDLockMode)) {
                //没有输入分库开锁人
                //给分库行机构添加锁
                if (StringUtils.isNotBlank(branchOrgIDOP) || StringUtils.isNotBlank(lockName)) {
                    addLockForORG(locksn, lockName, branchOrgID, taskADDBO.getTaskTypeName(),
                            taskADDBO.getCreateOP(), "1", (String) maps.get("deadLineDate"), (String) maps.get("startTime"));
                }
                maps.put("orgId", taskADDBO.getBranchOrgID());
                String nameById1 = znsTaskMapper.findNameById(taskADDBO.getBranchOrgID());
                maps.put("orgName", nameById1);
                //添加单人任务
                if (StringUtils.isNotBlank(lockName) && StringUtils.isNotBlank(locksn)) {
                    oneOpen(branchOrgIDOP, maps, lockName, locksn);
                }
            }//调拨双人开锁
            else if ("2".equals(branchOrgIDLockMode)) {
                //没有输入分库开锁人
                //给分库行机构添加锁
                if (StringUtils.isNotBlank(branchOrgIDOP) || StringUtils.isNotBlank(lockName)) {
                    addLockForORG(locksn, lockName, branchOrgID, taskADDBO.getTaskTypeName(), taskADDBO.getCreateOP(), "1",
                            (String) maps.get("deadLineDate"), (String) maps.get("startTime"));
                }
                String branchOrgId1 = taskADDBO.getBranchOrgID();
                String branchOrgName = znsTaskMapper.findNameById(taskADDBO.getBranchOrgID());
                if (StringUtils.isNotBlank(lockName)) {
                    doubleOpenLock(branchOrgIDOP,locksn, lockName, branchOrgId1, branchOrgName, maps);
                }
            }
        }
    }

    /**
     * 单人开锁
     */
    private void oneOpen(String openOps, Map<String, Object> maps, String lockName, String locksn) {
        if (!("".equals(openOps))) {
            //获取柜员名称-柜员id列表
            String[] gyOps = openOps.split(",");
            //获取锁列表
            String[] lockGYNames = lockName.split(",");
            //获取锁sn码
            String[] locksns = locksn.split(",");
            //柜员锁列表
            List<Terminal> gyList = new ArrayList<>();
            //通用锁列表
            List<Terminal> tyList = new ArrayList<>();
            //将柜员锁和柜员通锁数据分开
            for (String terminalSn : locksns) {
                Terminal terminal = terminalMapper.getTerminalBySn(terminalSn, TerminalTypeEnum.LOCK.getCode());
                if (LockTypeEnum.EMPLOYEE.getCode().equals(terminal.getLockType())) {
                    gyList.add(terminal);
                } else if (LockTypeEnum.EMPLOYEE_GENERAL.getCode().equals(terminal.getLockType())) {
                    tyList.add(terminal);
                }
            }
            //判断柜员锁是否为空
            if (!gyList.isEmpty()) {
                //柜员锁不为空，则任务为柜员锁开锁人对应自己的柜员锁+柜员铜锁
                for (Terminal gyLock : gyList) {
                    lockName = gyLock.getName();
                    locksn = gyLock.getTerminalSn();
                    //获取柜员id
                    String adminId = gyLock.getAdminId();
                    Operator operator = operatorMapper.getOperatorByOpId(adminId);
                    if (!tyList.isEmpty()) {
                        for (Terminal tyLock : tyList) {
                            StringBuilder gyNameBuilder = new StringBuilder(lockName);
                            StringBuilder lockSnBuilder = new StringBuilder(locksn);
                            lockName = String.valueOf(gyNameBuilder.append(",").append(tyLock.getName()));
                            locksn = String.valueOf(lockSnBuilder.append("/").append(tyLock.getTerminalSn()));
                        }
                    }
                    //任务主键
                    String primaryKey = genUniqueKey();
                    maps.put("taskID", primaryKey);
                    maps.put("lockMode", "1");
                    maps.put("openlockop", operator.getOpName());
                    maps.put("openlockopOrg", operator.getId());
                    maps.put("lockName", lockName);
                    locksn = locksn.replaceAll(",", "/");
                    maps.put("locksn", locksn);
                    addTask(maps, primaryKey);
                }
            } else {
                //未调拨  开始生成柜员任务
                for (int i = 0; i < gyOps.length; i++) {
                    //任务主键
                    String primaryKey = genUniqueKey();
                    String before = StringUtil.lastBefore(gyOps[i]);
                    String after = StringUtil.last(gyOps[i]);
                    maps.put("taskID", primaryKey);
                    maps.put("lockMode", "1");
                    maps.put("openlockop", before);
                    maps.put("openlockopOrg", after);
                    maps.put("lockName", lockName);
                    locksn = locksn.replaceAll(",", "/");
                    maps.put("locksn", locksn);
                    addTask(maps, primaryKey);
                }
            }
        } else {
            System.out.println("没有输入开锁人");
        }
    }

    private void addTask(Map<String, Object> maps, String primaryKey) {
        //插入柜员(主管)任务
        System.out.println(maps + "===输入参数");
        log.info("单人任务添加参数={}", maps);
        znsTaskMapper.addTask(maps);

        //插入任务审核表
        Map<Object, Object> taskCopyMap = new HashMap<>();
        String primaryKey2 = PrimaryKeyUtil.getPrimaryKey();
        String auditor = (String) maps.get("auditor");
        String createOP = (String) maps.get("createOP");
        String auditState = (String) maps.get("auditState");

        //审核表主键
        //根据编号查询所属机构及名称
        Map<String, String> auditMap = znsTaskMapper.selectIdAndNameById(auditor);
        taskCopyMap.put("AUDIT_OPId", auditor);
        taskCopyMap.put("AUDIT_OP", auditMap.get("opName"));
        taskCopyMap.put("AUDIT_OP_ORG", auditMap.get("orgId"));
        Map<String, String> createOPMap = znsTaskMapper.selectIdAndNameById(createOP);
        taskCopyMap.put("CREATE_AUDIT_OPId", createOP);
        taskCopyMap.put("CREATE_AUDIT_OP", createOPMap.get("opName"));
        taskCopyMap.put("CREATE_AUDIT_OP_ORG", createOPMap.get("orgId"));
        taskCopyMap.put("auditId", primaryKey2);
        taskCopyMap.put("taskId", primaryKey);
        taskCopyMap.put("auditaction", "添加任务编号为：" + primaryKey + "的任务");
        //查询当前登录机构的审核模式 同步or异步
        String orgId = (String) maps.get("orgId");
        String auditType = znsTaskMapper.selectAuditType(orgId);
        if (StringUtils.isNotBlank(auditState) && "2".equals(auditState)){
            auditType = "1";
        }
        if ("1".equals(auditType)) {
            //同步审核
            taskCopyMap.put("auditTime", DateUtil.getDateStr(DateUtil.YYYYMMDD_HHMMSS, new Date()));
            taskCopyMap.put("auditState", '2');
        } else {
            taskCopyMap.put("auditTime", null);
            taskCopyMap.put("auditState", '1');
        }
        znsTaskMapper.insertTaskCopy(taskCopyMap);
    }

    public static List<Pair<String, String>> combineTwoElement(List<String> list) {
        List<Pair<String, String>> resultList = Lists.newArrayListWithExpectedSize(list.size() * list.size() / 2);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        if (list.size() >= 2) {
            for (int j = 0; j < list.size(); j++) {
                resultList.addAll(ll(list.subList(j, list.size())));
            }
        }
        return resultList;
    }


    public static List<Pair<String, String>> ll(List<String> list) {
        List<Pair<String, String>> resultList = Lists.newArrayListWithExpectedSize(list.size() * list.size() / 2);
        for (int j = 1; j < list.size(); j++) {
            resultList.add(new Pair<>(list.get(0), list.get(j)));
        }
        return resultList;
    }

    /**
     * 生成任务唯一主键 9位
     */
    private String genUniqueKey() {
        String replace = UUID.randomUUID().toString().toUpperCase().replace("-", "").replace("A", "10").replace("B", "11").replace("C", "12")
                .replace("D", "13").replace("E", "14").replace("F", "15");
        String substring = replace.substring(0, 9);
        Integer count = znsTaskMapper.selectCountById(substring);
        if (count != null) {
            return genUniqueKey();
        } else {
            return substring;
        }
    }

    @Autowired
    private OrganizationService service;

    /**
     * 查询任务
     */
    @Override
    public BaseResult<DataGrid<TaskZNSDTO>> findTask(PaginationBO<TaskFindBO> taskFindBO, HttpServletRequest request) throws Exception {
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String state = taskFindBO.getParams().getState();
        if (StringUtils.isNotEmpty(taskFindBO.getParams().getOrgId())) {
            orgId = taskFindBO.getParams().getOrgId();
            // taskFindBO.getParams().setOrgId();
        }
        if (StringUtils.isNotBlank(taskFindBO.getParams().getTaskSendeeName())) {
            String[] split = taskFindBO.getParams().getTaskSendeeName().split(",");
            List<String> users = Arrays.asList(split);
            if (users.size() > 2) {
                return GetResult.getResultFail("接收人用户名数量超出限制");
            }
            List<Operator> operatorByRealNames = operatorMapper.getOperatorByRealNames(users);
            Map<String, List<Operator>> listMap = operatorByRealNames.stream().collect(Collectors.groupingBy(operator -> operator.getOpRealname()));
            ArrayList<String> list = new ArrayList<>();
            String s1 = split[0];
            List<Operator> operator2s = null;
            if (split.length > 1) {
                String s2 = split[1];
                operator2s = listMap.get(s2);
            }

            List<Operator> operators = listMap.get(s1);

            if (CollectionUtils.isEmpty(operators) && CollectionUtils.isEmpty(operator2s)) {
                return GetResult.getResultFail("用户名填写错误");
            }
            for (Operator operator : operators) {
                if (!CollectionUtils.isEmpty(operator2s)) {
                    for (Operator operator2 : operator2s) {
                        list.add(operator.getOpName() + "," + operator2.getOpName());
                    }
                } else {
                    list.add(operator.getOpName());
                }
            }
            taskFindBO.getParams().setTaskSendeeNames(list);


        }

        //获取当前机构及所有子机构
        List<Organization> orgIds = service.getOrgIds(orgId);
        for (Organization organization : orgIds) {
            taskFindBO.getParams().getListorgIds().add(organization.getOrgId());
        }
//        2022-11-12 23:12:15,2023-12-33 12:13:14
//        if (taskFindBO.getParams().getTimeScope()!=null &&
//        taskFindBO.getParams().getTimeScope()!="") {
//            String timeScope = taskFindBO.getParams().getTimeScope();
//            String beginTime = timeScope.trim().substring(0, 18);
//            String endTime = timeScope.trim().substring(20);
//            taskFindBO.getParams().setTimeScopeBegin(beginTime);
//            taskFindBO.getParams().setTimeScopeEnd(endTime);
//        }
//
//        if (taskFindBO.getParams().getTaskSendee()!=null && taskFindBO.getParams().getTaskSendee()!="" ){
//            taskFindBO.getParams().setTaskSendee("%"+taskFindBO.getParams().getTaskSendee()+"%");
//        }
//        if (taskFindBO.getParams().getTaskState()==null ||taskFindBO.getParams().getTaskState()==""){
//            taskFindBO.getParams().setTaskState("1");
//        }
        TaskFindBO boParams = taskFindBO.getParams();
        if (StringUtils.isBlank(boParams.getCreateOP()) ) {
            boParams.setOriginatorOp(opId);
        }
        PageHelper.startPage(taskFindBO.getPageNo(), taskFindBO.getPageSize());
        //查出来所有任务
        List<TaskZNSDTO> taskZNSDTOS = znsTaskMapper.selectByContidion(taskFindBO.getParams());
        for (TaskZNSDTO taskZNSDTO : taskZNSDTOS) {
            //查询已生效任务时将即将过期任务状态显示为已生效
            if (StrUtil.isNotBlank(state) && "1".equals(state)) {
                taskZNSDTO.setState("1");
            }

            if ("3".equals(taskZNSDTO.getTimeType())) {
                taskZNSDTO.setStartTimeConvert(String.valueOf(gettimeStemp(taskZNSDTO.getStartTime(), "yyyy-MM-dd")));
            } else {
                taskZNSDTO.setStartTimeConvert(String.valueOf(gettimeStemp(taskZNSDTO.getStartTime(), "")));
            }

            taskZNSDTO.setDeadLineDateConvert(String.valueOf(gettimeStemp(taskZNSDTO.getDeadLineDate(), "")));
            //根据登陆人编号 查询名字
            Map<String, String> stringStringMap = znsTaskMapper.selectIdAndNameById(taskZNSDTO.getCreateOPId());
            taskZNSDTO.setCreateOPName(stringStringMap.get("opName"));
            taskZNSDTO.setCreateOPRealName(stringStringMap.get("opRealName"));
            taskZNSDTO.setCreateAuditOpOrgName(stringStringMap.get("orgName"));
            //任务人员显示补充姓名+编号
            String userConvert = operatorService.userConvert(taskZNSDTO.getLockOp());
            taskZNSDTO.setLockOpConvert(userConvert);
            Operator operatorByOpName = operatorMapper.getOperatorByOpName(taskZNSDTO.getAuditOp());
            taskZNSDTO.setAuditOpRealName(operatorByOpName.getOpRealname());
            //获取时限类型
            String timeType = taskZNSDTO.getTimeType();
            if ("1".equals(timeType)) {
                //长期类型 2022-11-12 23:12:15 - 2023-12-33 12:13:14
                String datetimesta = taskZNSDTO.getDatetimesta();
                taskZNSDTO.setEffectivePeriod(datetimesta);
            } else if ("2".equals(timeType)) {
                //2022-11-12 ,  2023-12-33
                String dayDate = taskZNSDTO.getDayDate();
                //12:13:14-14:15:16
                String daytime = taskZNSDTO.getDaytime();

                taskZNSDTO.setEffectivePeriod(dayDate + "的" + daytime);
            } else if ("3".equals(timeType)) {
                //周设置
                String weekType = taskZNSDTO.getWeekType();
                String weekDay = taskZNSDTO.getWeekDay();
                String[] split = weekDay.split(",");
                //12:13:14-14:15:16
                String daytime = taskZNSDTO.getDaytime();
                String weekdays = "";
                for (String s : split) {
                    switch (s) {
                        case "1":
                            weekdays = weekdays + "周一,";
                            break;
                        case "2":
                            weekdays = weekdays + "周二,";
                            break;
                        case "3":
                            weekdays = weekdays + "周三,";
                            break;
                        case "4":
                            weekdays = weekdays + "周四,";
                            break;
                        case "5":
                            weekdays = weekdays + "周五,";
                            break;
                        case "6":
                            weekdays = weekdays + "周六,";
                            break;
                        case "7":
                            weekdays = weekdays + "周日,";
                            break;
                        default:
                            break;
                    }
                }
                if ("1".equals(weekType)) {
//                    1 近一周 2 近一月 3近一年
                    taskZNSDTO.setEffectivePeriod("近一周:" + weekdays + "=" + daytime);
                } else if ("2".equals(weekType)) {
                    taskZNSDTO.setEffectivePeriod("近一月:" + weekdays + "=" + daytime);
                } else if ("3".equals(weekType)) {
                    taskZNSDTO.setEffectivePeriod("近一年:" + weekdays + "=" + daytime);
                }
            }
            if (StringUtils.isNotBlank(taskZNSDTO.getWeekDay())) {
                taskZNSDTO.setWeekDay(taskZNSDTO.getWeekDay().replaceAll(",", "/"));
            }
        }
        //取分页信息
        PageInfo<TaskZNSDTO> pageInfo = new PageInfo<>(taskZNSDTOS);
        //设置返回结果
        DataGrid<TaskZNSDTO> dataGrid = new DataGrid<>();
        Long total = pageInfo.getTotal();
        dataGrid.setTotal(total.intValue());
        dataGrid.setRows(taskZNSDTOS);
        return GetResult.getResult(dataGrid);
    }

    @Override
    public BaseResult<TaskADDBO> findById(String taskId) {
        TaskADDBO taskADDBO = new TaskADDBO();
        TaskZNSDTO taskZNSDTO = znsTaskMapper.selectById(taskId);
        taskADDBO.setOrgIDforTask(taskZNSDTO.getTaskOrg());
        taskADDBO.setOrgName(taskZNSDTO.getTaskOrgName());
        taskADDBO.setTaskTypeName(taskZNSDTO.getTaskTypeName());
        taskADDBO.setWhoOpenWhoClose(taskZNSDTO.getWhoOpenwhoClose());
        taskADDBO.setOnceTheLock(taskZNSDTO.getOnceTheLock());
        taskADDBO.setTimeType(taskZNSDTO.getTimeType());
        taskADDBO.setDateTime(taskZNSDTO.getDatetimesta());
        taskADDBO.setDayDate(taskZNSDTO.getDayDate());
        taskADDBO.setDayTime(taskZNSDTO.getDaytime());
        taskADDBO.setWeekType(taskZNSDTO.getWeekType());
        taskADDBO.setWeekDay(taskZNSDTO.getWeekDay());
        taskADDBO.setLockMode(taskZNSDTO.getLockMode());

        ArrayList<String> list = new ArrayList<>();
        if ("2".equals(taskZNSDTO.getLockMode())) {
            String[] split = taskZNSDTO.getLockOp().split(",");
            for (String s : split) {
                StringBuffer buffer = new StringBuffer();
                buffer.append(s);
                buffer.append("-");

                Operator operatorByOpName = operatorMapper.getOperatorByOpName(s);
                buffer.append(operatorByOpName.getId());
                list.add(buffer.toString());
            }
        } else {
            StringBuffer buffer = new StringBuffer();
            buffer.append(taskZNSDTO.getLockOp());
            buffer.append("-");
            Operator operatorByOpName = operatorMapper.getOperatorByOpName(taskZNSDTO.getLockOp());
            buffer.append(operatorByOpName.getId());
            list.add(buffer.toString());
        }


        taskADDBO.setOpenLockOP(StringUtils.join(list, ","));
        //分行库机构id
        taskADDBO.setBranchOrgID(taskZNSDTO.getBrcOrgId());
        taskADDBO.setBranchOrgName(taskZNSDTO.getBrcOrgName());
        taskADDBO.setBranchOrgIDOP(taskZNSDTO.getBrcOrgIdOp());
        taskADDBO.setBranchOrgIDLockMode(taskZNSDTO.getBrcOrgMode());

        taskADDBO.setAssociatedTrunkLockType(taskZNSDTO.getAssociatedTrunkLokcType());
        taskADDBO.setLockName(taskZNSDTO.getLockname());
        taskADDBO.setLocksn(taskZNSDTO.getLockSn());
        taskADDBO.setTransportEscorts(taskZNSDTO.getTransportEscorts());
        taskADDBO.setTransportCar(taskZNSDTO.getTransportCar());
        taskADDBO.setTransportCompany(taskZNSDTO.getTransportCompany());
        taskADDBO.setTaskState(taskZNSDTO.getTaskState());
        taskADDBO.setAuditState(taskZNSDTO.getAuditState());
        taskADDBO.setIssuedState(taskZNSDTO.getIssuedState());
        taskADDBO.setSecurityPolicy(taskZNSDTO.getSecurityPolicy());
        taskADDBO.setTrunkId(taskZNSDTO.getTrunkId());
        return GetResult.getResult(taskADDBO);
    }

    /**
     * 删除任务
     */
    @Override
    public BaseResult deleteTask(TaskDeleteBO taskDelete, HttpServletRequest request) {
        try {
            String opId = TokenUtil.getOpId(request.getHeader("token"));
            String orgId = TokenUtil.getOrgId(request.getHeader("token"));
            String opName = TokenUtil.getOpName(request.getHeader("token"));
            //定义日志信息
            String logName = TblLogConst.TASK_DELETE;
            String operationDesc = "用户" + opName + "对任务编号为" + taskDelete.getTaskId() + "进行删除";
            String taskIds = taskDelete.getTaskId();
            String[] split = taskIds.split(",");
            znsTaskMapper.updateTaskState(split);
            for (String taskId : split) {
                TaskZNSDTO taskZNSDTO = znsTaskMapper.selectById(taskId);
                String lockSn = taskZNSDTO.getLockSn();
                String[] lockSns = lockSn.split("/");
                for (String lock : lockSns) {
                    Terminal terminal = terminalMapper.getTerminalBySn(lock, TerminalTypeEnum.LOCK.getCode());
                    if (ObjectUtil.isNotNull(terminal) && StringUtils.isNotBlank(terminal.getOldOrg()) && StringUtils.isNotBlank(taskZNSDTO.getBrcOrgId())) {
                        //先清除锁具在新机构中的开锁任务
                        resetTask(terminal);
                        terminalMapper.resetLockOrg(terminal.getId());
                    }
                }
            }
            operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
            return GetResult.getResultSuccess("删除成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return GetResult.getResultFail("删除失败");
        }

    }

    /**
     * 分配审核任务 修改审核任务表
     */
    @Override
    public BaseResult assignmentAuditTask(TaskAuditBO taskAuditBO) {
        try {
            String taskIDs = taskAuditBO.getTaskId();
            String[] split = taskIDs.split(",");
            for (String taskId : split) {
                //修改审核任务表
                znsTaskMapper.updateTaskCopy(taskId);

            }
            return GetResult.getResultSuccess("分配任务成功");
        } catch (Exception e) {
            return GetResult.getResultFail("分配任务失败");
        }
    }

    /**
     * 下发任务
     */
    @Override
    public BaseResult issuedTask(TaskissuedBO taskissued, HttpServletRequest request) {
        try {
            String opId = TokenUtil.getOpId(request.getHeader("token"));
            String orgId = TokenUtil.getOrgId(request.getHeader("token"));
            String opName = TokenUtil.getOpName(request.getHeader("token"));
            //定义日志信息
            String logName = TblLogConst.TASK_ISSUE;
            String operationDesc = "用户" + opName + "下发任务，任务编号为：" + taskissued.getTaskID();
            znsTaskMapper.issuedTask(taskissued);
            operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
            return GetResult.getResultSuccess("修改数据库下发状态成功");
        } catch (Exception e) {
            return GetResult.getResultFail("修改数据库下发状态失败");
        }

    }

    /***
     * 更新任务
     */
    @Override
    public BaseResult insertNewTask(TaskADDBO taskADDBO) {
        return null;
    }

    @Override
    public BaseResult<List<OrgDTO>> findPeopleByOrg(OrgBO orgBO) {
        List<OrgDTO> peopleByOrg = znsTaskMapper.findPeopleByOrg(orgBO);
        BaseResult<List<OrgDTO>> objectBaseResult = new BaseResult<>();
        objectBaseResult.setData(peopleByOrg);
        objectBaseResult.setDataMessage("当前机构下人员");
        objectBaseResult.setDataCode("00");
        return objectBaseResult;
    }

    @Override
    public BaseResult<List<LockDTO>> findLockByOP(LockBO lock) {
        List<LockDTO> peopleByOrg = znsTaskMapper.findLockByOP(lock);
        List<String> openLockSnList = taskMapper.getOpenLockSn();
        List<String> removes = new ArrayList<>();
        for (int i = 0; i < peopleByOrg.size(); i++) {
            LockDTO lockDto = peopleByOrg.get(i);
            for (String openLockSn : openLockSnList) {
                String[] openLockSns = openLockSn.split("/");
                for (String lockSn : openLockSns) {
                    if (lockSn.equals(lockDto.getLockSn())) {
                        removes.add(lockSn);
                    }
                }
            }
        }
        peopleByOrg = peopleByOrg.stream().filter(s -> !removes.contains(s.getLockSn())).collect(toList());
        BaseResult<List<LockDTO>> objectBaseResult = new BaseResult<>();
        objectBaseResult.setData(peopleByOrg);
        objectBaseResult.setDataMessage("当前机构下人员角色对应锁具");
        objectBaseResult.setDataCode("00");
        return objectBaseResult;
    }

    @Override
    public BaseResult<DataGrid<TaskZNSDTO>> findTaskIssued(PaginationBO<TaskFindBOForInssued> taskFindBOForInssued, HttpServletRequest request) {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        //定义日志信息
        String logName = TblLogConst.TASK_READ;
        String operationDesc = "用户" + opName + "进行任务读取";
        PageHelper.startPage(taskFindBOForInssued.getPageNo(), taskFindBOForInssued.getPageSize());
        if (taskFindBOForInssued.getParams().getTaskIdForSea() != null && taskFindBOForInssued.getParams().getTaskIdForSea() != "" && taskFindBOForInssued.getParams().getTaskIdForSea().length() > 0) {
            taskFindBOForInssued.getParams().setTaskIds(Arrays.asList(taskFindBOForInssued.getParams().getTaskIdForSea().split(",")));
        }
        if ("".equals(taskFindBOForInssued.getParams().getTaskIds()) || taskFindBOForInssued.getParams().getTaskIds() == null || taskFindBOForInssued.getParams().getTaskIds().size() == 0) {
            List<String> strings = new ArrayList<>();
            strings.add("1");
            taskFindBOForInssued.getParams().setTaskIds(strings);
        } else {
            List<String> taskIdList = new ArrayList<>();
            List<String> taskIds = taskFindBOForInssued.getParams().getTaskIds();
            for (String taskId : taskIds) {
                String id = "";
                id = String.format("%09d", Long.parseLong(taskId));
                taskIdList.add(id);
            }
            taskFindBOForInssued.getParams().setTaskIds(taskIdList);
        }
        List<TaskZNSDTO> taskIssued = znsTaskMapper.findTaskIssued(taskFindBOForInssued.getParams());
        for (TaskZNSDTO taskZNSDTO : taskIssued) {
            //根据登陆人编号 查询名字
            Map<String, String> stringStringMap = znsTaskMapper.selectIdAndNameById(taskZNSDTO.getCreateOPId());
            taskZNSDTO.setCreateOPName(stringStringMap.get("opName"));
            taskZNSDTO.setCreateAuditOpOrgName(stringStringMap.get("orgName"));

            taskZNSDTO.setCreateOPRealName(stringStringMap.get("opRealName"));
            //任务人员显示补充姓名+编号
            String userConvert = operatorService.userConvert(taskZNSDTO.getLockOp());
            taskZNSDTO.setLockOpConvert(userConvert);
            Operator operatorByOpName = operatorMapper.getOperatorByOpName(taskZNSDTO.getAuditOp());
            taskZNSDTO.setAuditOpRealName(operatorByOpName.getOpRealname());

            //if (!"2".equals(taskZNSDTO.getTaskState())) {
            //    String deadLineDate = taskZNSDTO.getDeadLineDate();
            //    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //    try {
            //
            //        Date parse = simpleDateFormat.parse(deadLineDate);
            //        Date date = new Date();
            //        if (date.compareTo(parse) > 0) {
            //            //已过期
            //            taskZNSDTO.setTaskState("2");
            //        } else {
            //            taskZNSDTO.setTaskState("1");
            //        }
            //    } catch (Exception e) {
            //        return GetResult.getResultFail("日期错误");
            //    }
            //}
            //获取时限类型
            String timeType = taskZNSDTO.getTimeType();
            if ("1".equals(timeType)) {
                //长期类型 2022-11-12 23:12:15 - 2023-12-33 12:13:14
                String datetimesta = taskZNSDTO.getDatetimesta();
                taskZNSDTO.setEffectivePeriod(datetimesta);
            } else if ("2".equals(timeType)) {
                //2022-11-12 ,  2023-12-33
                String dayDate = taskZNSDTO.getDayDate();
                //12:13:14-14:15:16
                String daytime = taskZNSDTO.getDaytime();
                taskZNSDTO.setEffectivePeriod(dayDate + "的" + daytime);
            } else if ("3".equals(timeType)) {
                //周设置
                String weekType = taskZNSDTO.getWeekType();
                String weekDay = taskZNSDTO.getWeekDay();
                String[] split = weekDay.split(",");
                //12:13:14-14:15:16
                String daytime = taskZNSDTO.getDaytime();
                String weekdays = "";
                for (String s : split) {
                    switch (s) {
                        case "1":
                            weekdays = weekdays + "周一,";
                            break;
                        case "2":
                            weekdays = weekdays + "周二,";
                            break;
                        case "3":
                            weekdays = weekdays + "周三,";
                            break;
                        case "4":
                            weekdays = weekdays + "周四,";
                            break;
                        case "5":
                            weekdays = weekdays + "周五,";
                            break;
                        case "6":
                            weekdays = weekdays + "周六,";
                            break;
                        case "7":
                            weekdays = weekdays + "周日,";
                            break;
                        default:
                            break;
                    }
                }
                if ("1".equals(weekType)) {
//                    1 近一周 2 近一月 3近一年
                    taskZNSDTO.setEffectivePeriod("近一周:" + weekdays + "==" + daytime);
                } else if ("2".equals(weekType)) {
                    taskZNSDTO.setEffectivePeriod("近一月:" + weekdays + "==" + daytime);
                } else if ("3".equals(weekType)) {
                    taskZNSDTO.setEffectivePeriod("近一年:" + weekdays + "==" + daytime);
                }
            }
        }
        operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
        //取分页信息
        PageInfo<TaskZNSDTO> pageInfo = new PageInfo<>(taskIssued);
        //设置返回结果
        DataGrid<TaskZNSDTO> dataGrid = new DataGrid<>();
        Long total = pageInfo.getTotal();
        dataGrid.setTotal(total.intValue());
        dataGrid.setRows(taskIssued);
        return GetResult.getResult(dataGrid);
    }


    /**
     * 将审核表状态改为审核通过或者审核未通过
     */
    @Override
    public BaseResult auditTask(TaskCopyBO taskCopyBO, HttpServletRequest request) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        List<String> list = taskCopyBO.getTasKIds();
        for (String taskId : list) {
            String[] split = taskId.split(",");
            for (String id : split) {
                TaskCopy taskCopy = znsTaskMapper.getTaskCopy(id);
                if (ObjectUtil.isNull(taskCopy)) {
                    return GetResult.getResultErr("任务编号为" + id + "的审核信息已审核");
                }
                if (!opId.equals(taskCopy.getAuditOp())) {
                    return GetResult.getResultFail("当前用户没有权限任务编号为" + id + "的审核信息");
                }
            }
        }
        taskCopyBO.setAuditTime(format);
        //审核通过 审核表审核状态改为 审核通过 任务表 任务id改为任务生效 默认添加任务时任务就已生效
        String auditType = taskCopyBO.getAuditType();
        if ("2".equals(auditType)) {
            //通过
            znsTaskMapper.auditTask(taskCopyBO);
        } else if ("3".equals(auditType)) {
            //不通过 修改审核表状态 将任务表 任务 改为失效
            znsTaskMapper.auditTask(taskCopyBO);
            TaskDeleteBO taskDeleteBO = new TaskDeleteBO();
            List<String> tasKIds = taskCopyBO.getTasKIds();
            for (String tasKId : tasKIds) {
                taskDeleteBO.setTaskId(tasKId);
                String[] split = tasKId.split(",");
                znsTaskMapper.updateTaskState(split);
                for (String taskId : split) {
                    TaskZNSDTO taskZNSDTO = znsTaskMapper.selectById(taskId);
                    String lockSn = taskZNSDTO.getLockSn();
                    String[] lockSns = lockSn.split("/");
                    for (String lock : lockSns) {
                        Terminal terminal = terminalMapper.getTerminalBySn(lock, TerminalTypeEnum.LOCK.getCode());
                        if (StringUtils.isNotBlank(terminal.getOldOrg())) {
                            terminalMapper.resetLockOrg(terminal.getId());
                        }
                    }
                }
            }


        }
        return GetResult.getResultSuccess("审核成功");
    }

    @Override
    public BaseResult<DataGrid<TaskZNSDTO>> taskListForLogin(PaginationBO<TaskListForLoginBO> taskListForLoginBO, HttpServletRequest request) throws Exception {
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        if (StringUtils.isBlank(taskListForLoginBO.getParams().getOrgId())) {
            String org = getOrgIdAllChild(orgId);
            taskListForLoginBO.getParams().setOrgId(org);
        } else {
            //得到本机构的所有下属机构id号
            String org = getOrgIdAllChild(taskListForLoginBO.getParams().getOrgId());
            taskListForLoginBO.getParams().setOrgId(org);
        }
        PageHelper.startPage(taskListForLoginBO.getPageNo(), taskListForLoginBO.getPageSize());
        List<TaskZNSDTO> taskZNSDTOS = znsTaskMapper.taskListForLogin(taskListForLoginBO.getParams());
        for (TaskZNSDTO taskZNSDTO : taskZNSDTOS) {
            Map<String, String> stringStringMap = znsTaskMapper.selectIdAndNameById(taskZNSDTO.getCreateOPId());
            taskZNSDTO.setCreateOPName(stringStringMap.get("opName"));
            taskZNSDTO.setCreateOPRealName(stringStringMap.get("opRealName"));
            taskZNSDTO.setCreateAuditOpOrgName(stringStringMap.get("orgName"));
            Operator operatorByOpName = operatorMapper.getOperatorByOpName(taskZNSDTO.getAuditOp());
            taskZNSDTO.setAuditOpRealName(operatorByOpName.getOpRealname());

            //获取时限类型
            String timeType = taskZNSDTO.getTimeType();
            if ("1".equals(timeType)) {
                //长期类型 2022-11-12 23:12:15 - 2023-12-33 12:13:14
                String datetimesta = taskZNSDTO.getDatetimesta();
                taskZNSDTO.setEffectivePeriod(datetimesta);
            } else if ("2".equals(timeType)) {
                //2022-11-12 ,  2023-12-33
                String dayDate = taskZNSDTO.getDayDate();
                //12:13:14-14:15:16
                String daytime = taskZNSDTO.getDaytime();

                taskZNSDTO.setEffectivePeriod(dayDate + "的" + daytime);
            } else if ("3".equals(timeType)) {
                //周设置
                String weekType = taskZNSDTO.getWeekType();
                String weekDay = taskZNSDTO.getWeekDay();
                String[] split = weekDay.split(",");
                //12:13:14-14:15:16
                String daytime = taskZNSDTO.getDaytime();
                String weekdays = "";
                for (String s : split) {
                    switch (s) {
                        case "1":
                            weekdays = weekdays + "周一,";
                            break;
                        case "2":
                            weekdays = weekdays + "周二,";
                            break;
                        case "3":
                            weekdays = weekdays + "周三,";
                            break;
                        case "4":
                            weekdays = weekdays + "周四,";
                            break;
                        case "5":
                            weekdays = weekdays + "周五,";
                            break;
                        case "6":
                            weekdays = weekdays + "周六,";
                            break;
                        case "7":
                            weekdays = weekdays + "周日,";
                            break;
                        default:
                            break;
                    }
                }
                if ("1".equals(weekType)) {
//                    1 近一周 2 近一月 3近一年
                    taskZNSDTO.setEffectivePeriod("近一周:" + weekdays + "==" + daytime);
                } else if ("2".equals(weekType)) {
                    taskZNSDTO.setEffectivePeriod("近一月:" + weekdays + "==" + daytime);
                } else if ("3".equals(weekType)) {
                    taskZNSDTO.setEffectivePeriod("近一年:" + weekdays + "==" + daytime);
                }
            }
        }
        //取分页信息
        PageInfo<TaskZNSDTO> pageInfo = new PageInfo<>(taskZNSDTOS);
        //设置返回结果
        DataGrid<TaskZNSDTO> dataGrid = new DataGrid<>();
        Long total = pageInfo.getTotal();
        dataGrid.setTotal(total.intValue());
        dataGrid.setRows(taskZNSDTOS);
        return GetResult.getResult(dataGrid);

    }

    @Override
    public void taskReviewExport(HttpServletResponse response, TaskListForLoginBO taskListForLoginBO, HttpServletRequest request) {
        try {
            String opId = TokenUtil.getOpId(request.getHeader("token"));
            String orgId = TokenUtil.getOrgId(request.getHeader("token"));
            String opName = TokenUtil.getOpName(request.getHeader("token"));
            operatorLogService.insert("任务审核导出", "任务审核导出", "1", opId, opName, orgId);
            // 执行查询
            //获取当前机构及下属机构id集合
            if (StringUtils.isBlank(taskListForLoginBO.getOrgId())) {
                String org = getOrgIdAllChild(orgId);
                taskListForLoginBO.setOrgId(org);
            } else {
                //得到本机构的所有下属机构id号
                String org = getOrgIdAllChild(taskListForLoginBO.getOrgId());
                taskListForLoginBO.setOrgId(org);
            }
            List<TaskExportDTO> list = znsTaskMapper.taskReviewExport(taskListForLoginBO);
            if (list == null || list.isEmpty()) {
                throw new RuntimeException("无数据无需导出");
            }
            String title = "任务审核导出" + Math.random() + ".xls";
            String[] headers = new String[]{"审核流水号", "任务编号", "发起审核操作员", "审核人", "审核人编号", "审核人所属机构编号", "审核人所属机构名称", "审核状态", "审核备注", "审核时间"};

            List<Object[]> dataList;
            dataList = list.stream().map(taskCopy -> {
                Object[] obj = new Object[headers.length];
                obj[0] = taskCopy.getAuditId();
                obj[1] = taskCopy.getTaskId();
                obj[2] = taskCopy.getCreateAuditOp();
                obj[3] = taskCopy.getAuditOp();
                obj[4] = taskCopy.getAuditOpId();
                obj[5] = taskCopy.getAuditOpOrg();
                obj[6] = taskCopy.getAuditOrgName();
                obj[7] = taskCopy.getAuditState();
                obj[8] = taskCopy.getAuditRemark();
                obj[9] = taskCopy.getAuditTime();
                return obj;
            }).collect(toList());
            OutputStream out = null;
            // 防止中文乱码
            String headStr = "attachment; filename=\"" + new String(title.getBytes("gb2312"), "ISO8859-1") + "\"";
            response.setContentType("octets/stream");
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setHeader("Content-Disposition", headStr);
            out = response.getOutputStream();
            ExcelOutput ex = new ExcelOutput(title, headers, dataList);
            ex.export(out);
            log.info("任务审核导出");
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            HeaderResult.setFailHeader(request, response, e.getMessage());
        }

    }

    public String getOrgIdAllChild(String orgId) throws Exception {
        List<Organization> orgList = organizationService.getOrgIds(orgId);
        StringBuilder sb = new StringBuilder();
        for (Organization organization : orgList) {
            sb.append(organization.getOrgId()).append(",");
        }
        int size = sb.toString().length() - 1;
        return sb.toString().substring(0, size);
    }

    @Override
    public BaseResult<AuditTaskDetailDTO> auditTaskDetail(AuditTaskDetailBO auditTaskDetailBO) {
        //根据任务编号 查询任务
        TaskZNSDTO taskZNSDTO = znsTaskMapper.auditTaskDetail(auditTaskDetailBO);

        //获取时限类型
        String timeType = taskZNSDTO.getTimeType();
        if ("1".equals(timeType)) {
            //长期类型 2022-11-12 23:12:15 - 2023-12-33 12:13:14
            String datetimesta = taskZNSDTO.getDatetimesta();
            taskZNSDTO.setEffectivePeriod(datetimesta);
        } else if ("2".equals(timeType)) {
            //2022-11-12 ,  2023-12-33
            String dayDate = taskZNSDTO.getDayDate();
            //12:13:14-14:15:16
            String daytime = taskZNSDTO.getDaytime();

            taskZNSDTO.setEffectivePeriod(dayDate + "的" + daytime);
        } else if ("3".equals(timeType)) {
            //周设置
            String weekType = taskZNSDTO.getWeekType();
            String weekDay = taskZNSDTO.getWeekDay();
            String[] split = weekDay.split(",");
            //12:13:14-14:15:16
            String daytime = taskZNSDTO.getDaytime();
            String weekdays = "";
            for (String s : split) {
                switch (s) {
                    case "1":
                        weekdays = weekdays + "周一,";
                        break;
                    case "2":
                        weekdays = weekdays + "周二,";
                        break;
                    case "3":
                        weekdays = weekdays + "周三,";
                        break;
                    case "4":
                        weekdays = weekdays + "周四,";
                        break;
                    case "5":
                        weekdays = weekdays + "周五,";
                        break;
                    case "6":
                        weekdays = weekdays + "周六,";
                        break;
                    case "7":
                        weekdays = weekdays + "周日,";
                        break;
                    default:
                        break;
                }
            }
            if ("1".equals(weekType)) {
//                    1 近一周 2 近一月 3近一年
                taskZNSDTO.setEffectivePeriod("近一周:" + weekdays + "=" + daytime);
            } else if ("2".equals(weekType)) {
                taskZNSDTO.setEffectivePeriod("近一月:" + weekdays + "=" + daytime);
            } else if ("3".equals(weekType)) {
                taskZNSDTO.setEffectivePeriod("近一年:" + weekdays + "=" + daytime);
            }
        }

        AuditTaskDetailDTO auditTaskDetailDTO = new AuditTaskDetailDTO();
        Map<String, String> stringStringMap = znsTaskMapper.selectIdAndNameById(taskZNSDTO.getCreateOPId());
        taskZNSDTO.setCreateOPName(stringStringMap.get("opName"));
        taskZNSDTO.setCreateAuditOpOrgName(stringStringMap.get("orgName"));

        Map<String, String> stringStringMap2 = znsTaskMapper.selectIdAndNameById(taskZNSDTO.getAuditOpId());
        taskZNSDTO.setAuditOpOrgName(stringStringMap2.get("orgName"));
        if (StringUtils.isNotBlank(taskZNSDTO.getBrcOrgId())){
            String orgName = znsTaskMapper.findNameById(taskZNSDTO.getBrcOrgId());
            taskZNSDTO.setBrcOrgName(orgName);
        }



        auditTaskDetailDTO.setTaskZNSDTONew(taskZNSDTO);
        BaseResult<AuditTaskDetailDTO> objectBaseResult = new BaseResult<>();
        objectBaseResult.setData(auditTaskDetailDTO);
        objectBaseResult.setDataCode("00");
        objectBaseResult.setDataMessage("审核详情");
        return objectBaseResult;
    }

    @Override
    public BaseResult findAllORG() {
        List<OrgTypeDTO> allORG = znsTaskMapper.findAllORG();
        BaseResult<List<OrgTypeDTO>> objectBaseResult = new BaseResult<>();
        objectBaseResult.setData(allORG);
        objectBaseResult.setDataMessage("押运机构");
        objectBaseResult.setDataCode("00");
        return objectBaseResult;
    }

    @Override
    public BaseResult findBoxByOrg(LockBO lock) {
        List<BoxDTO> boxByOrg = znsTaskMapper.findBoxByOrg(lock);
        BaseResult<List<BoxDTO>> objectBaseResult = new BaseResult<>();
        objectBaseResult.setData(boxByOrg);
        objectBaseResult.setDataCode("00");
        objectBaseResult.setDataMessage("当前机构下的尾箱");
        return objectBaseResult;
    }

    @Override
    public BaseResult<List<LockDTO>> findLockByBox(BoxBO boxBo) {
        //根据尾箱编号查询锁具
        List<LockDTO> all = new ArrayList<LockDTO>();
        List<String> trunkSn = boxBo.getTrunkSn();
        for (String box : trunkSn) {
            Map<String, String> lockIds = znsTaskMapper.findLockByBox(box);
            String trunkLockOne = lockIds.get("trunkLockOne");
            String trunkLockTwo = lockIds.get("trunkLockTwo");

            //根据锁具编号查询锁具
            List<LockDTO> lockById = znsTaskMapper.findLockById(trunkLockOne);
            List<LockDTO> lockById1 = znsTaskMapper.findLockById(trunkLockTwo);
            all.addAll(lockById);
            all.addAll(lockById1);
        }

        BaseResult<List<LockDTO>> objectBaseResult = new BaseResult<>();
        objectBaseResult.setDataCode("00");
        objectBaseResult.setData(all);
        objectBaseResult.setDataMessage("当前尾箱对应锁具");
        return objectBaseResult;
    }

    int strCode = 0;
    @Autowired
    private OperatorService operatorService;

    @Override
    public BaseResult openLock(OpenLockBO openLockBO) {
        //根据当前登陆人编号查询 id
        String s = znsTaskMapper.selectIdByopId(openLockBO.getOpId());
        if (!openLockBO.getOpenlockopId().contains(s)) {
            return GetResult.getResultFail("当前登陆人没有操作权限");
        }
        AuditPasswordBo auditPasswordBo = new AuditPasswordBo();
        auditPasswordBo.setAuditor(openLockBO.getOpId());
        auditPasswordBo.setOpPwd(openLockBO.getPwd());
        try {
            //判断账号密码 是否正确
            operatorService.auditPassword(auditPasswordBo);
        } catch (Exception e) {
            e.printStackTrace();
            Log.getLog().info("判断账号密码接口出错");
            return GetResult.getResultFail("判断账号密码接口出错");
        }
        String start = "7E";
        String version = "0105";
        //根据尾箱sn码查询尾箱信息
        BoxInfo boxInfo = znsTaskMapper.selectBoxBySn(openLockBO);
        if ("0".equals(boxInfo.getTaskStatus())) {
            return GetResult.getResultFail("在途中尾箱不能远程开锁");
        }
        StringBuilder strCode = new StringBuilder(Integer.toHexString(this.strCode).toUpperCase());
        this.strCode++;
        if (this.strCode == 65535) {
            this.strCode = 0;
        }
        if (strCode.length() < 4) {
            do {
                strCode.insert(0, "0");
            } while (strCode.length() < 4);
        }
        String strAddress = boxInfo.getImeiId() + "000000000";
        String functionCode = "4411";
        String frameType = "00";

        Calendar now = Calendar.getInstance();
        String year = String.valueOf(now.get(Calendar.YEAR));
        int last = Integer.parseInt(year.substring(2));

        String strTime = DataUtils.byteToHex(last) + DataUtils.byteToHex(now.get(Calendar.MONTH) + 1) + DataUtils.byteToHex(now.get(Calendar.DAY_OF_MONTH))
                + DataUtils.byteToHex(now.get(Calendar.HOUR_OF_DAY)) + DataUtils.byteToHex(now.get(Calendar.MINUTE)) + DataUtils.byteToHex(now.get(Calendar.SECOND));
        String cmd = "01";
        System.out.println(strTime);

        System.out.println(version + "," + strCode + "," + strAddress + "," + functionCode);
        String check = version + strCode + strAddress + functionCode + frameType + strTime + cmd;
        check = check.replace(" ", "");
        byte[] crcData = CrcUtils.concatAll(DataUtils.hexToByteArray(check), CrcUtils.CRC16(DataUtils.hexToByteArray(check)));
        byte[] crcdata = new byte[]{crcData[crcData.length - 2], crcData[crcData.length - 1]};

        String crc = DataUtils.byteToHexStr(crcdata);
        System.out.println(DataUtils.byteToHexStr(crcData));
        System.out.println(crc);
        String end = "7E";
        String data = start + version + strCode + strAddress + functionCode + frameType + strTime + cmd + crc + end;
        String ascii = DataUtils.byteToHexStr(data.getBytes(StandardCharsets.US_ASCII));

        System.out.println(ascii.length());
        String strCmd = "02" + DataUtils.byteToHex(ascii.length() / 2) + ascii;
        System.out.println(strCmd);
        JSONObject result = null;
        try {
            result = testApiWithSignature(strCmd, openLockBO.getOpId(), openLockBO.getTrunkSn().replace(" ", ""));
            String msg = result.getString("msg");

            if (result.getIntValue("code") == 0) {

                return GetResult.getResultSuccess("远程开锁成功");
            } else {
                return GetResult.getResultFail(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();

            return GetResult.getResultFail("系统异常");
        }

    }

    @Override
    public BaseResult findLockInfo(FindLockInfoBo f) {
        List<findLockInfoDTO> lockInfo = znsTaskMapper.findLockInfo(f);
        for (findLockInfoDTO findLockInfoDto : lockInfo) {
            String locKSn = findLockInfoDto.getLocKSn();
            findLockInfoDto.setLockSns(Arrays.asList(locKSn.split("/")));
        }
        BaseResult<List<findLockInfoDTO>> objectBaseResult = new BaseResult<>();
        objectBaseResult.setData(lockInfo);
        objectBaseResult.setDataMessage("任务id对应锁列表");
        objectBaseResult.setDataCode("00");
        return objectBaseResult;
    }

    @Override
    public BaseResult<List<TaskZNSDTO>> findTaskIssuedtwo(TaskFindBOForInssued taskFindBOForInssued) {
        if (taskFindBOForInssued.getTaskIds().size() <= 0 || taskFindBOForInssued.getTaskIds() == null) {
            BaseResult<List<TaskZNSDTO>> listBaseResult = new BaseResult<>();
            return listBaseResult;
        }
        List<String> taskIdList = new ArrayList<>();
        List<String> taskIds = taskFindBOForInssued.getTaskIds();
        for (String taskId : taskIds) {
            String id = "";
            id = String.format("%09d", Long.parseLong(taskId));
            taskIdList.add(id);
        }
        taskFindBOForInssued.setTaskIds(taskIdList);
        List<TaskZNSDTO> taskIssued = znsTaskMapper.findTaskIssued(taskFindBOForInssued);
        //for (TaskZNSDTO taskZNSDTO : taskIssued) {
        //    if (!"2".equals(taskZNSDTO.getTaskState())) {
        //        String deadLineDate = taskZNSDTO.getDeadLineDate();
        //        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //        try {
        //            Date parse = simpleDateFormat.parse(deadLineDate);
        //            Date date = new Date();
        //            if (date.compareTo(parse) > 0) {
        //                //已过期
        //                taskZNSDTO.setTaskState("2");
        //            } else {
        //                taskZNSDTO.setTaskState("1");
        //            }
        //        } catch (Exception e) {
        //            return GetResult.getResultFail("日期错误");
        //
        //        }
        //    }
        //}
        BaseResult<List<TaskZNSDTO>> objectBaseResult = new BaseResult<>();
        objectBaseResult.setDataMessage("已下发任务");
        objectBaseResult.setData(taskIssued);
        objectBaseResult.setDataCode("00");
        return objectBaseResult;
    }

    @Override
    public BaseResult<List<OrgRoleDTO>> findOperatorByOrg(TaskSceOrgBO orgBO) {
        List<OrgRoleDTO> operators = znsTaskMapper.findOperatorByOrg(orgBO);
        BaseResult<List<OrgRoleDTO>> objectBaseResult = new BaseResult<>();
        objectBaseResult.setData(operators);
        objectBaseResult.setDataMessage("当前场景机构下人员");
        objectBaseResult.setDataCode("00");
        return objectBaseResult;
    }

    @Override
    public void resetTask(Terminal ter) {
        //清除锁具在新机构中的开锁任务
        TaskFindBO taskFindBO=new TaskFindBO();
        taskFindBO.setOrgId(ter.getOrgId());
        taskFindBO.setLockSn(ter.getTerminalSn());
        taskFindBO.setTimeScopeBegin(ter.getStartTime());
        taskFindBO.setTimeScopeEnd(ter.getEffectTime());
        List<TaskZNSDTO> taskZNSDTOS = znsTaskMapper.selectByCon(taskFindBO);
        if(CollectionUtil.isNotEmpty(taskZNSDTOS)){
            List<String> taskIds = taskZNSDTOS.stream().map(TaskZNSDTO::getTaskId).collect(toList());
            String[] split=new String[taskIds.size()];
            split=taskIds.toArray(split);
            znsTaskMapper.updateTaskState(split);
        }
    }

    private JSONObject testApiWithSignature(String payload, String operator, String deviceId) throws Exception {

        AepDeviceCommandClient client = AepDeviceCommandClient.newClient().appKey("fFnM6gdK5u5").appSecret("z1EnCFfneO").build();
        CreateCommandRequest request = new CreateCommandRequest();
        request.setParamMasterKey("ed1a58ccc74e4117ae97b6f9433b0ae8");
        JSONObject jsonObject = new JSONObject();
        JSONObject content = new JSONObject();
        content.put("dataType", 2);
        content.put("payload", payload);
        jsonObject.put("content", content);
        jsonObject.put("deviceId", deviceId);
        jsonObject.put("operator", operator);
        jsonObject.put("productId", "15000405");
        jsonObject.put("ttl", 0);
        jsonObject.put("deviceGroupId", "");
        jsonObject.put("level", 1);
        request.setBody(jsonObject.toString().getBytes(StandardCharsets.UTF_8));
        CreateCommandResponse createCommandResponse = client.CreateCommand(request);
        System.out.println(createCommandResponse);
        client.shutdown();
        return JSONObject.parseObject(new String(createCommandResponse.getBody()));
    }

    private long gettimeStemp(String time, String format) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (!"".equals(format)) {
            simpleDateFormat = new SimpleDateFormat(format);
        }
        long timeStemp = 0;
        try {
            Date date = simpleDateFormat.parse(time);

            timeStemp = date.getTime();

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return timeStemp;
    }
}
